package com.hyk.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyk.domain.SysRole;
import com.hyk.domain.SysUser;
import com.hyk.domain.SysUserRole;
import com.hyk.dto.AdminUserDto;
import com.hyk.mapper.SysUserMapper;
import com.hyk.service.SysRoleService;
import com.hyk.service.SysUserRoleService;
import com.hyk.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService{

    private Snowflake snowflake = new Snowflake(1,1);

    @Resource
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public Page<SysUser> findList(Page<SysUser> page, String mobile, String fullname) {

        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(mobile)) {
            queryWrapper.like("mobile",mobile);
        }
        if (StringUtils.isNotBlank(fullname)) {
            queryWrapper.like("fullname",fullname);
        }
        queryWrapper.orderByDesc("last_update_time");
        Page<SysUser> userPage = page(page, queryWrapper);

        List<SysUser> records = userPage.getRecords();
        for (SysUser sysUser: records) {
            List<SysRole> userRole = sysRoleService.findUserRole(sysUser.getId());
            StringBuilder stringBuffer = new StringBuilder();
            for (int i=0;i<userRole.size();i++){
                stringBuffer.append(userRole.get(i).getId());
                if(i != userRole.size()-1){
                    stringBuffer.append(",");
                }
            }
            sysUser.setRole_strings(stringBuffer.toString());
        }
        return userPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUser(SysUser sysUser) {
        Long id = snowflake.nextId();
        sysUser.setId(id);
        sysUser.setPassword(new BCryptPasswordEncoder().encode(sysUser.getPassword()));
        save(sysUser);
        saveUserRole(sysUser,id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(SysUser sysUser) {
        updateById(sysUser);
        sysUserRoleService.removeUserRoleByUserId(sysUser.getId());
        saveUserRole(sysUser,sysUser.getId());
    }

    @Override
    public Map<Long, AdminUserDto> getAdminUser(List<Long> ids) {
        if(CollectionUtils.isEmpty(ids)){
            return null;
        }
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id",ids);
        List<SysUser> list = list(queryWrapper);
        if (CollectionUtils.isEmpty(list)){
            return null;
        }
        List<AdminUserDto> adminUserDtos = list.stream().map(user -> {
            AdminUserDto userDto = new AdminUserDto();
            BeanUtils.copyProperties(user,userDto);
            return userDto;
        }).collect(Collectors.toList());
        Map<Long,AdminUserDto> map = new HashMap<>();
        for (AdminUserDto a : adminUserDtos) {
            map.put(a.getId(),a);
        }
        return map;
    }

    private void saveUserRole(SysUser sysUser, Long id) {
        String[] roleIds = sysUser.getRole_strings().split(",");

        List<SysUserRole> roles = new ArrayList<>();

        for(String roleId: roleIds){
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(Long.parseLong(roleId));
            sysUserRole.setUserId(id);
            roles.add(sysUserRole);
        }
        sysUserRoleService.saveBatch(roles);
    }
}
